package com.efounder.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.activity.CreateOrderActivity;
import com.efounder.activity.ProductDetailsActivity;
import com.efounder.adapter.CartExpandableAdapter;
import com.efounder.addressselector.OnAddressSelectedListener;
import com.efounder.addressselector.RightDialog;
import com.efounder.addressselector.model.City;
import com.efounder.addressselector.model.County;
import com.efounder.addressselector.model.Province;
import com.efounder.addressselector.model.Street;
import com.efounder.bean.CartEditEvent;
import com.efounder.bean.CartEditVisibleEvent;
import com.efounder.bean.CartListBean;
import com.efounder.bean.CartNumberEvent;
import com.efounder.bean.UpdateCartBadgeEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.KeyboardUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.efounder.utils.MallRequestUtil.CART_ADD_OR_DELETE_URL;
import static com.efounder.utils.MallRequestUtil.CART_LIST_URL;
import static com.efounder.utils.MallRequestUtil.GOOD_COLLECT_AOR;

/**
 * Created by will on 18-1-15.
 * 购物车Fragment
 * @author will
 */

public class MallCartFragment extends BaseFragment implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener {

    private static String TAG = "MallCartFragment";
    private ImageView ivBack, ivMessage;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout llNetworkErrorView;
    private TextView tvCart, tvEdit, tvAddress, tvTotalPrice, tvCheckout, tvSaveToFavor,
            tvDeleteSelected, tvDeleteInvalid;
    private ExpandableListView mExpandableListView;
    private LinearLayout llCartNoItem;
    private ConstraintLayout llEdit;
    private RelativeLayout rlTotal;
    private CheckBox checkBox;
    private View view;
    private double allPrice = 0.00;
    private CartListBean cartListBean;
    private List<CartListBean.MyshopcartBean> myshopcartBeanList = new ArrayList<>();
    private List<CartListBean.MyshopcartBean.GoodsBean> deleteGoods = new ArrayList<>();
    private List<CartListBean.MyshopcartBean.GoodsBean> checkItems = new ArrayList<>();
    private CartExpandableAdapter cartExpandableAdapter;
    private int cartItemNum = 0;
    private boolean hideTitle = false;

    public MallCartFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.layout_cart, container, false);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(this);
        llNetworkErrorView = (LinearLayout) view.findViewById(R.id.ll_network_error);
        TextView tvReload = (TextView) llNetworkErrorView.findViewById(R.id.tv_network_reload);
        tvReload.setOnClickListener(this);
        EventBus.getDefault().register(this);
        initParams();
        initData();
        initView(view);
        return view;
    }

    /**
     * 是否隐藏标题栏
     */
    private void initParams() {
        if (getArguments() != null && getArguments().getBoolean("hideTitle", false)) {
            hideTitle = true;
        }
    }

    private void initView(View view) {
        if (hideTitle) {
            view.findViewById(R.id.rl_title).setVisibility(View.GONE);
        }
        ivBack = (ImageView) view.findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvCart = (TextView) view.findViewById(R.id.tv_cart);
        llCartNoItem = (LinearLayout) view.findViewById(R.id.ll_cart_no_item);
        ivMessage = (ImageView) view.findViewById(R.id.iv_message);
        ivMessage.setOnClickListener(this);
        tvEdit = (TextView) view.findViewById(R.id.tv_edit);
        tvEdit.setOnClickListener(this);
        tvAddress = (TextView) view.findViewById(R.id.tv_address);
        llEdit =  view.findViewById(R.id.ll_bottom_edit);
        tvSaveToFavor = (TextView) view.findViewById(R.id.save_to_favor);
        tvSaveToFavor.setOnClickListener(this);
        tvDeleteSelected = (TextView) view.findViewById(R.id.delete_selected);
        tvDeleteSelected.setOnClickListener(this);
        tvDeleteInvalid = view.findViewById(R.id.delete_invalid);
        tvDeleteInvalid.setOnClickListener(this);
        rlTotal = (RelativeLayout) view.findViewById(R.id.rl_total);
        mExpandableListView = (ExpandableListView) view.findViewById(R.id.expandablelist);
//        cartExpandableAdapter = new CartExpandableAdapter(cartStores, getActivity());
//        mExpandableListView.setClipChildren(false);
//        mExpandableListView.setAdapter(cartExpandableAdapter);
//        for (int i = 0; i < cartStores.size(); i++) {
//            mExpandableListView.expandGroup(i);
//        }
//        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
//                return true;
//            }
//        });
        checkBox = (CheckBox) view.findViewById(R.id.id_cb_select_all);
        tvTotalPrice = (TextView) view.findViewById(R.id.tv_total_price);
        tvCheckout = (TextView) view.findViewById(R.id.tv_checkout);
        tvCheckout.setOnClickListener(this);
        if (allPrice == 0.00) {
            tvCheckout.setClickable(false);
        } else {
            tvCheckout.setClickable(true);
        }
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view instanceof CheckBox) {
                    CheckBox checkBox = (CheckBox) view;
                    cartExpandableAdapter.setupAllChecked(checkBox.isChecked());
                }
            }
        });
        mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
//                if (cartListBean.getMyshopcart().get(i).getGoods().get(i1).getGood().getGoodStatus() == 0 ||
//                        cartListBean.getMyshopcart().get(i).getGoods().get(i1).getGood().getGoodSkus().get(0).getStockNumber() <= 0) {
//                    return false;
//                }
                Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
                intent.putExtra("goodbh", cartListBean.getMyshopcart().get(i).getGoods().get(i1).getGood().getGoodId());
                getActivity().startActivity(intent);
                return false;
            }
        });

    }

    private void initAdapter() {
        myshopcartBeanList = cartListBean.getMyshopcart();
        for (int i = 0; i < myshopcartBeanList.size(); i++) {
            CartListBean.MyshopcartBean myshopcartBean = cartListBean.getMyshopcart().get(i);
            for (int j = 0; j < myshopcartBean.getGoods().size(); j++) {
                CartListBean.MyshopcartBean.GoodsBean goodsBean = myshopcartBean.getGoods().get(j);
                for (int k = 0; k < checkItems.size(); k++) {
                    if (checkItems.get(k).getGood().getGoodId().equals(goodsBean.getGood().getGoodId())
                            && checkItems.get(k).getGood().getGoodSkus().get(0).getSkuId()
                            .equals(goodsBean.getGood().getGoodSkus().get(0).getSkuId())) {
                        goodsBean.setSelect(true);
                    }
                }
            }
            if (cartExpandableAdapter != null) {
                myshopcartBean.setSelect(cartExpandableAdapter.dealOneParentAllChildIsChecked(i));
            }
        }
        cartExpandableAdapter = new CartExpandableAdapter(myshopcartBeanList, getActivity());
        mExpandableListView.setClipChildren(false);
        mExpandableListView.setAdapter(cartExpandableAdapter);
        for (int i = 0; i < cartListBean.getMyshopcart().size(); i++) {
            mExpandableListView.expandGroup(i);
        }
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });
        cartExpandableAdapter.setOnAllCheckedBoxNeedChangeListener(new CartExpandableAdapter.OnAllCheckedBoxNeedChangeListener() {
            @Override
            public void onCheckedBoxNeedChange(boolean allParentIsChecked) {
                checkBox.setChecked(allParentIsChecked);
                checkBox.setEnabled(!cartExpandableAdapter.isAllGoodInvalid());
            }
        });

        cartExpandableAdapter.setOnGoodsCheckedChangeListener(new CartExpandableAdapter.OnGoodsCheckedChangeListener() {
            @Override
            public void onGoodsCheckedChange(int totalCount, double totalPrice, double totalTax, List<CartListBean.MyshopcartBean.GoodsBean> items) {
                allPrice = totalPrice;
                tvTotalPrice.setText(ResStringUtil.getString(R.string.common_text_money_unit) + TCMathUtil.retainAsignDecimalsWithZero(totalPrice, 2));
                if (totalCount != 0) {
                    tvCheckout.setBackground(getResources().getDrawable(R.drawable.accent_square));
                    tvCheckout.setText(ResStringUtil.getString(R.string.mail_frame_settlement) + totalCount + ")");
                    tvCheckout.setClickable(true);
                } else {
                    tvCheckout.setBackground(getResources().getDrawable(R.drawable.gray_square));
                    tvCheckout.setText(R.string.mail_settlement);
                    tvCheckout.setClickable(false);
                }
                checkItems = items;
            }
        });
//        cartExpandableAdapter.setOnAmountChangeListener(new CartExpandableAdapter.OnAdapterAmountChangeListener() {
//            @Override
//            public void onAmountChange() {
////                                refreshData();
//            }
//        });
        cartExpandableAdapter.setOnGoodsDeleteChangeListener(new CartExpandableAdapter.OnGoodsDeleteChangeListener() {
            @Override
            public void onGoodsDeleteChange(List<CartListBean.MyshopcartBean.GoodsBean> deleteItems) {
                deleteGoods = deleteItems;
            }
        });
        checkBox.setChecked(cartExpandableAdapter.dealAllParentIsChecked());
        checkBox.setEnabled(!cartExpandableAdapter.isAllGoodInvalid());
//        cartExpandableAdapter.setupAllChecked(checkBox.isChecked());
    }
    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, CART_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    cartItemNum = 0;
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    cartListBean = gson.fromJson(response, CartListBean.class);
                    if ("success".equals(cartListBean.getResult())) {
                        llNetworkErrorView.setVisibility(View.GONE);
                        tvEdit.setClickable(true);
                        if (cartListBean.getMyshopcart().size() > 0) {
                            llCartNoItem.setVisibility(View.GONE);
                            tvEdit.setVisibility(View.VISIBLE);
                            EventBus.getDefault().post(new CartEditVisibleEvent(true));
                        } else {
                            llCartNoItem.setVisibility(View.VISIBLE);
                            tvEdit.setVisibility(View.GONE);
                            EventBus.getDefault().post(new CartEditVisibleEvent(false));
                        }
                        initAdapter();
//                        }
                        //购物车标题显示数量
                        for (CartListBean.MyshopcartBean cartStoreitem : cartListBean.getMyshopcart()) {
                            cartItemNum += cartStoreitem.getGoods().size();
                        }
                        if (cartItemNum != 0) {
                            tvCart.setText(ResStringUtil.getString(R.string.mail_frame_shop_car) + "(" + cartItemNum + ")");
                            EventBus.getDefault().post(new CartNumberEvent(cartItemNum));
                        }else {
                            tvCart.setText(R.string.mail_shop_car);
                            EventBus.getDefault().post(new CartNumberEvent(0));
                        }
                    }else {
                        llNetworkErrorView.setVisibility(View.VISIBLE);
                        tvEdit.setClickable(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    llNetworkErrorView.setVisibility(View.VISIBLE);
                    tvEdit.setClickable(false);
                }
            }

            @Override
            public void onFail(String error) {
                llNetworkErrorView.setVisibility(View.VISIBLE);
                tvEdit.setClickable(false);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        initView(view);
        refreshData();
    }

    public void refreshData() {
        tvEdit.setText(ResStringUtil.getString(R.string.mail_edit));
        swipeRefreshLayout.setRefreshing(true);
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, CART_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    cartItemNum = 0;
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    cartListBean = gson.fromJson(response, CartListBean.class);
                    if (cartListBean.getResult().equals("success")) {
                        if (cartListBean.getMyshopcart().size() > 0) {
                            llCartNoItem.setVisibility(View.GONE);
                            tvEdit.setVisibility(View.VISIBLE);
                            EventBus.getDefault().post(new CartEditVisibleEvent(true));
                        } else {
                            llCartNoItem.setVisibility(View.VISIBLE);
                            tvEdit.setVisibility(View.GONE);
                            EventBus.getDefault().post(new CartEditVisibleEvent(false));
                        }
                        llEdit.setVisibility(View.GONE);
                        rlTotal.setVisibility(View.VISIBLE);
                        tvCheckout.setVisibility(View.VISIBLE);
                        initAdapter();
                        //购物车标题显示数量
                        for (CartListBean.MyshopcartBean cartStoreitem : cartListBean.getMyshopcart()) {
                            cartItemNum += cartStoreitem.getGoods().size();
                        }
                        if (cartItemNum != 0) {
                            tvCart.setText(ResStringUtil.getString(R.string.mail_frame_shop_car) + " (" + cartItemNum + ")");
                            EventBus.getDefault().post(new CartNumberEvent(cartItemNum));
                        }else {
                            tvCart.setText(R.string.mail_shop_car);
                            EventBus.getDefault().post(new CartNumberEvent(0));
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFail(String error) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        if (checkItems == null){
            tvTotalPrice.setText(ResStringUtil.getString(R.string.common_text_money_unit)+"0.00");
            tvCheckout.setBackground(getResources().getDrawable(R.drawable.gray_square));
            tvCheckout.setText(R.string.mail_settlement);
            tvCheckout.setClickable(false);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_edit) {
            if (tvEdit.getText().toString().equals(ResStringUtil.getString(R.string.mail_complete))) {
                //隐藏键盘
                KeyboardUtils.hideSoftInput(getActivity());
                for(int i = 0;i<myshopcartBeanList.size();i++){
                    myshopcartBeanList.get(i).setEditing(false);
                }

                refreshData();
                EventBus.getDefault().post(new UpdateCartBadgeEvent());
                cartExpandableAdapter.dealPrice();
                tvEdit.setText(R.string.mail_edit);
                llEdit.setVisibility(View.GONE);
                rlTotal.setVisibility(View.VISIBLE);
                tvCheckout.setVisibility(View.VISIBLE);
            } else {
                tvEdit.setText(R.string.mail_complete);
                if (myshopcartBeanList.size() > 0) {
                    for(int i = 0;i<myshopcartBeanList.size();i++){
                        myshopcartBeanList.get(i).setEditing(true);
                    }
                    cartExpandableAdapter.notifyDataSetChanged();
                    llEdit.setVisibility(View.VISIBLE);
                    rlTotal.setVisibility(View.GONE);
                    tvCheckout.setVisibility(View.GONE);
                }
            }
        } else if (id == R.id.delete_selected) {
            deleteGoods();
        }else if (id == R.id.save_to_favor){
            saveToFavor();
        } else if (id == R.id.iv_back) {
            getActivity().finish();
        } else if (id == R.id.iv_message) {
            //todo 消息

        } else if (id == R.id.ll_address) {
            final RightDialog dialog = new RightDialog(getActivity());
            dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
                @Override
                public void onAddressSelected(Province province, City city, County county, Street street) {
                    tvAddress.setText(province.name + city.name);
                    dialog.dismiss();
                }
            });
            dialog.show();
        } else if (id == R.id.tv_checkout) {
            Intent intent = new Intent(getActivity(), CreateOrderActivity.class);
            Map<String, String> map = new HashMap<>();
            JSONArray jsonArray = new JSONArray();
            for (CartListBean.MyshopcartBean.GoodsBean goodsBean:
                 checkItems) {
                map.put("goodbh", goodsBean.getGood().getGoodId());
                map.put("goodNum", String.valueOf(goodsBean.getNum()));
                map.put("skuId", goodsBean.getGood().getGoodSkus().get(0).getSkuId());
                jsonArray.put(new JSONObject(map));
            }
            intent.putExtra("checkItems", jsonArray.toString());
            startActivity(intent);
        } else if (id == R.id.tv_network_reload) {
            initData();
        } else if (id == R.id.delete_invalid) {
            //删除失效商品
            deleteInvalidGoods();
        }
    }

    @Subscribe (threadMode = ThreadMode.MAIN)
    public void onCartEditChangeEvent(CartEditEvent cartEditEvent) {
        boolean isEditing = cartEditEvent.isEditing();
        if (isEditing) {
            //隐藏键盘
            KeyboardUtils.hideSoftInput(getActivity());
            for(int i = 0;i<myshopcartBeanList.size();i++){
                myshopcartBeanList.get(i).setEditing(false);
            }
            refreshData();
            EventBus.getDefault().post(new UpdateCartBadgeEvent());
            cartExpandableAdapter.dealPrice();
            tvEdit.setText(R.string.mail_edit);
            llEdit.setVisibility(View.GONE);
            rlTotal.setVisibility(View.VISIBLE);
            tvCheckout.setVisibility(View.VISIBLE);
        } else {
            if (myshopcartBeanList.size() > 0) {
                for(int i = 0;i<myshopcartBeanList.size();i++){
                    myshopcartBeanList.get(i).setEditing(true);
                }
                cartExpandableAdapter.notifyDataSetChanged();
                llEdit.setVisibility(View.VISIBLE);
                rlTotal.setVisibility(View.GONE);
                tvCheckout.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 删除选中的商品
     */
    private void deleteGoods() {
        if (deleteGoods.size() != 0) {
            new AlertDialog.Builder(getActivity()).setMessage(ResStringUtil.getString(R.string.mail_take_this) + deleteGoods.size() + ResStringUtil.getString(R.string.mail_shop_delete))
                    .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            LoadingDataUtilBlack.show(getActivity());
                            HashMap<String, String> map = new HashMap<>();
                            map.put("userId", EnvironmentVariable.getUserName());
                            try {
                                JSONArray jsonArray = new JSONArray();
                                for (CartListBean.MyshopcartBean.GoodsBean cartItem : deleteGoods) {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("goodbh", cartItem.getGood().getGoodId());
                                    jsonObject.put("goodNum", 0);
                                    jsonObject.put("skuId", cartItem.getGood().getGoodSkus().get(0).getSkuId());
                                    jsonArray.put(jsonObject);
                                }
                                map.put("goods", jsonArray.toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            MallRequestUtil.getRequest(TAG, CART_ADD_OR_DELETE_URL, map, new MallRequestUtil.MallRequestCallback() {
                                @Override
                                public void onSuccess(String response) {
                                    LoadingDataUtilBlack.dismiss();
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        if(response!=null&&jsonObject.optString("result").equals("success")){
                                            removeDeleteGoodsList(false);
                                            EventBus.getDefault().post(new UpdateCartBadgeEvent());
                                        }else if ("fail".equals(jsonObject.optString("result"))){
                                            ToastUtil.showToastCenter(jsonObject.optString("msg"));
                                        } else {
                                            ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_fail));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }

                                @Override
                                public void onFail(String error) {
                                    LoadingDataUtilBlack.dismiss();
                                    ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_fail));
                                }
                            });

                        }
                    }).setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        } else {
            ToastUtil.showToast(getActivity(), R.string.mail_please_select_delete_good);
        }
    }

    /**
     * 删除失效的商品
     */
    private void deleteInvalidGoods() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < cartListBean.getMyshopcart().size(); i++) {
                CartListBean.MyshopcartBean myshopcartBean = cartListBean.getMyshopcart().get(i);
                for (int j = 0; j < myshopcartBean.getGoods().size(); j++) {
                    CartListBean.MyshopcartBean.GoodsBean goodsBean = myshopcartBean.getGoods().get(j);
                    if (goodsBean.getGood().getGoodSkus().get(0).getStockNumber() > 0 &&
                            goodsBean.getGood().getGoodStatus() == 1){
                        continue;
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("goodbh", goodsBean.getGood().getGoodId());
                    jsonObject.put("goodNum", 0);
                    jsonObject.put("skuId", goodsBean.getGood().getGoodSkus().get(0).getSkuId());
                    jsonArray.put(jsonObject);
                }
            }
            map.put("goods", jsonArray.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LoadingDataUtilBlack.show(getActivity());
        MallRequestUtil.getRequest(TAG, CART_ADD_OR_DELETE_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if(response!=null&&jsonObject.optString("result").equals("success")){
                        removeDeleteGoodsList(true);
                        EventBus.getDefault().post(new UpdateCartBadgeEvent());
                    }else if ("fail".equals(jsonObject.optString("result"))){
                        ToastUtil.showToastCenter(jsonObject.optString("msg"));
                    } else {
                        ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_fail));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToastCenter(getResources().getString(R.string.mall_delete_fail));
            }
        });
    }

    /**
     * 将选中的商品移入收藏夹
     */
    private void saveToFavor() {
        if (deleteGoods.size() != 0) {
            HashMap<String, String> map = new HashMap<>();
            StringBuilder stringBuilder = new StringBuilder();
            for (CartListBean.MyshopcartBean.GoodsBean cartItem : deleteGoods) {
                stringBuilder.append(cartItem.getGood().getGoodId()).append(";");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            map.put("userId", EnvironmentVariable.getUserName());
            map.put("goodBhs", stringBuilder.toString());
            map.put("operate", "add");
            LoadingDataUtilBlack.show(getActivity());
            MallRequestUtil.getRequest(TAG, GOOD_COLLECT_AOR, map, new MallRequestUtil.MallRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    LoadingDataUtilBlack.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optString("result").equals("success")) {
                            ToastUtils.showShort(R.string.mall_save_to_favor_success);
//                            tvEdit.performClick();
                        } else {
                            String error = jsonObject.optString("msg");
                            if (error == null || "".equals(error)) {
                                error = ResStringUtil.getString(R.string.mall_save_to_favor_fail);
                            }
                            ToastUtils.showShort(error);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        ToastUtils.showShort(R.string.mall_save_to_favor_fail);
                    }

                }

                @Override
                public void onFail(String error) {
                    LoadingDataUtilBlack.dismiss();
                    ToastUtils.showShort(R.string.mall_save_to_favor_fail);
                }
            });
        }else {
            ToastUtil.showToast(getActivity(), R.string.mall_please_select_favorite_good);
        }
    }

    @Override
    public void onRefresh() {
        refreshData();
    }

    @Override
    public void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }


    /**
     * 移除要删除的商品集合
     */
    private void removeDeleteGoodsList(boolean invalid){
        //临时商品集合类
        List<CartListBean.MyshopcartBean> tempShopCartBeanList = myshopcartBeanList;
        //移除删除的商品 犹豫这边获取的是一个删除商品的集合  没有店铺信息  暂时使用双重for移除
        for(int i = 0;i<myshopcartBeanList.size();i++){
            if (invalid) {
                for (int j = 0; j < myshopcartBeanList.get(i).getGoods().size(); j++) {
                    if (myshopcartBeanList.get(i).getGoods().get(j).getGood().getGoodStatus() == 0 ||
                            myshopcartBeanList.get(i).getGoods().get(j).getGood().getGoodSkus().get(0).getStockNumber() <= 0) {
                        myshopcartBeanList.get(i).getGoods().remove(j);
                    }
                }
            } else {
                for (int j = 0; j < deleteGoods.size(); j++) {
                    List<CartListBean.MyshopcartBean.GoodsBean> goodsBeans =
                            myshopcartBeanList.get(i).getGoods();
                    for (int k = 0; k < goodsBeans.size(); k++) {
                        if (goodsBeans.get(k).getGood().getGoodId()
                                .equals(deleteGoods.get(j).getGood().getGoodId()) &&
                                goodsBeans.get(k).getGood().getGoodSkus().get(0).getSkuId()
                                        .equals(deleteGoods.get(j).getGood().getGoodSkus()
                                                .get(0).getSkuId())) {
                            //移除
                            goodsBeans.remove(k);
                        }
                    }
                }
            }
        }
        //计算商品列表是否还有商品，
        int goodsNum = 0;
        for(int i = 0;i<myshopcartBeanList.size();i++){
            for(int j = 0;j<myshopcartBeanList.get(i).getGoods().size();j++){
                goodsNum++;
            }
        }
        for(int i = 0;i<tempShopCartBeanList.size();i++){
            //如果当前店铺中没有商品，移除当前店铺
            if(myshopcartBeanList.get(i).getGoods().size()==0){
                myshopcartBeanList.remove(i);
            }
        }
        //如果商品列表为0显示占位布局
        if (goodsNum > 0) {
            llCartNoItem.setVisibility(View.GONE);
            tvEdit.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new CartEditVisibleEvent(true));
        } else {
            llCartNoItem.setVisibility(View.VISIBLE);
            tvEdit.setVisibility(View.GONE);
            EventBus.getDefault().post(new CartEditVisibleEvent(false));
        }
        //设置购物车标题的数量
        if (goodsNum != 0) {
            tvCart.setText(ResStringUtil.getString(R.string.mail_frame_shop_car) + " (" + goodsNum + ")");
            EventBus.getDefault().post(new CartNumberEvent(goodsNum));
        }else {
            tvCart.setText(R.string.mail_shop_car);
            EventBus.getDefault().post(new CartNumberEvent(0));
        }
        if (!invalid) {
            deleteGoods.clear();
        }
        cartExpandableAdapter.deleteGoodsUpdate(myshopcartBeanList);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}